package microphone;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;

public class ServerThread extends Thread {

    private int serverPort;
    private boolean running = true;
    private MicrophoneThread microphone;
    private short callerId;
    private DatagramSocket socket = null;
    public LinkedBlockingQueue<byte[]> soundQueue = new LinkedBlockingQueue<byte[]>();

    public ServerThread(int serverPort, MicrophoneThread microphone) {
        this.serverPort = serverPort;
        this.microphone = microphone;
    }

    @Override
    public void run() {
        running = true;
        try {
            socket = new DatagramSocket(serverPort);
            while (running) {

                byte[] buffer = new byte[microphone.getBufferSize() + 18];

                DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
                socket.receive(dp);
                
                ByteBuffer bb = ByteBuffer.wrap(buffer);
                short caller = bb.getShort();
                short head = bb.getShort();
                short tail = bb.getShort();
                bb.getInt();

                float[] fData = new float[microphone.getBufferSize()];
                int k = 0;
                for (int i = 0; i < head; i++) {
                    fData[i] = 0;
                    k++;
                }
                while (bb.hasRemaining()) {
                    fData[k] = bb.getShort();
                    k++;
                }

                for (int j = 0; j < tail; j++) {
                    if (k < fData.length) {
                        fData[k] = 0;
                        k++;
                    }
                }

                soundQueue.add(AudioProcessing.inverse(fData, microphone.getFormat()));
            }
        } catch (IOException ex) {
            System.err.println(ex);
        }
    }

    public void stopRunning() {
        running = false;
    }
}
